#!/bin/bash

# 脚本用于将项目中所有非UTF-8编码的文件转换为UTF-8编码

PROJECT_ROOT="/home/xxcubt/tt/ralylibtest"
TEMP_DIR="/tmp/utf8_conversion"

# 创建临时目录
mkdir -p "$TEMP_DIR"

echo "检查并转换项目中的非UTF-8文件..."

# 查找所有cpp和h文件
find "$PROJECT_ROOT" -name "*.cpp" -o -name "*.h" | while read file; do
    # 获取文件编码
    encoding=$(file -i "$file" | cut -d'=' -f2)
    
    echo "检查文件: $file (编码: $encoding)"
    
    # 如果不是utf-8编码，则进行转换
    if [[ "$encoding" != "utf-8" && "$encoding" != "us-ascii" ]]; then
        echo "  -> 转换文件: $file"
        
        # 根据原编码进行转换
        case "$encoding" in
            "iso-8859-1")
                iconv -f ISO-8859-1 -t UTF-8 "$file" > "$TEMP_DIR/$(basename "$file")"
                ;;
            "gbk")
                iconv -f GBK -t UTF-8 "$file" > "$TEMP_DIR/$(basename "$file")"
                ;;
            "gb2312")
                iconv -f GB2312 -t UTF-8 "$file" > "$TEMP_DIR/$(basename "$file")"
                ;;
            *)
                echo "  -> 未知编码，尝试使用iconv自动检测"
                iconv -f "$encoding" -t UTF-8 "$file" > "$TEMP_DIR/$(basename "$file")"
                ;;
        esac
        
        # 替换原文件
        mv "$TEMP_DIR/$(basename "$file")" "$file"
        echo "  -> 已转换为UTF-8"
    else
        echo "  -> 已经是UTF-8编码，无需转换"
    fi
done

echo "转换完成！"